import NProgress from 'nprogress';
import { isNavigationFailure } from 'vue-router';

import router from '@/routers';

import { loginRoute, storageKey } from '@/types/constants';

const whiteRouteList = [loginRoute.path];

router.beforeEach((to, from, next) => {
  NProgress.start();
  console.log(from);
  if (whiteRouteList.includes(to.path)) {
    next();
    NProgress.done();
    return;
  }

  const hasToken = localStorage.getItem(storageKey.accesstoken);
  if (hasToken) {
    if (to.path === loginRoute.path || to.name === loginRoute.name) {
      next({ path: '/' }); // 已登录,则去主页
    } else {
      // 做用户权限认证
      next();
    }
    NProgress.done();
    return;
  }

  next({ path: `/login?redirect=${to.path}` });
  NProgress.done();
});

router.afterEach((to, from, failure) => {
  NProgress.done(true);
  if (isNavigationFailure(failure)) {
    console.log('to', to);
    console.log('from', from);
    console.log('failed navigation:', failure);
  }
});
